// 给form表单添加提交事件
let form = document.querySelector('#form');
let usernameInp = document.getElementsByName('username')[0];
let pwdInp = document.getElementsByName('pwd')[0];
let repwdInp = document.getElementsByClassName('repwd')[0];
let profileInp = document.querySelector('#profile');
let showProfile = document.querySelector('#showProfile');
import { addUserReq } from '../../api';


// 头像预览
profileInp.onchange = function(e) {
    // console.log("改变了");
    // 拿到你选择的头像信息
    let fileReader = new FileReader();

    let file = e.target.files[0];

    // 使用base64编码格式去读取文件
    fileReader.readAsDataURL(file);

    fileReader.onload = function() {
        let url = fileReader.result;
        showProfile.src = url;
    }
}


form.onsubmit = async function(e) {
    e.preventDefault();

    let username = usernameInp.value;
    let pwd = pwdInp.value;
    let repwd = repwdInp.value;
    let profileVal = profileInp.value;

    if (!username.trim() || !pwd.trim()) {
        alert("请填写用户名和密码");
        return;
    }

    if (pwd !== repwd) {
        alert('请保证俩次输入的密码一致');
        return;
    }

    // 验证头像是否已选
    if (!profileVal) {
        alert("请选择头像");
        return;
    }

    // 用户提交的数据
    let data = new FormData(form)

    let { code } = await addUserReq(data);

    // console.log(res);
    if (code === 2000) {
        alert('添加成功！');
        window.location.href = '/users.html'
    }

}